<template>
  <div class="activities-page">
    <el-card class="activities-card">
      <template #header>
        <div class="card-header">
          <h3>等待签到</h3>
          <el-button type="primary" @click="fetchActivities" :loading="loading">
            <el-icon><Refresh /></el-icon>
            刷新
          </el-button>
        </div>
      </template>

      <el-table :data="activities" v-loading="loading" style="width: 100%">
        <el-table-column prop="teacherName" label="老师姓名" />
        <el-table-column prop="type" label="签到类型" width="120">
          <template #default="{ row }">
            <el-tag :type="getSignTypeTag(row.type)">
              {{ getSignTypeText(row.type) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="startTime" label="开始时间">
          <template #default="{ row }">
            {{ formatDateTime(row.startTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="endTime" label="结束时间">
          <template #default="{ row }">
            {{ formatDateTime(row.endTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200">
          <template #default="{ row }">
            <!-- 普通签到 -->
            <el-button
              v-if="row.type === 'normal'"
              type="primary"
              @click="handleNormalSign(row)"
              :loading="row.signing"
            >
              立即签到
            </el-button>
            <!-- 签到码签到 -->
            <el-button
              v-if="row.type === 'code'"
              type="warning"
              @click="handleCodeSign(row)"
              :loading="row.signing"
            >
              输入签到码
            </el-button>
            <!-- 二维码签到 -->
            <el-button
              v-if="row.type === 'qr'"
              type="success"
              @click="handleQRSign(row)"
              :loading="row.signing"
            >
              扫码签到
            </el-button>
            <!-- 九宫格签到 -->
            <el-button
              v-if="row.type === 'gesture'"
              type="info"
              @click="handleGestureSign(row)"
              :loading="row.signing"
            >
              九宫格签到
            </el-button>
            <!-- 位置签到 -->
            <el-button
              v-if="row.type === 'location'"
              type="danger"
              @click="handleLocationSign(row)"
              :loading="row.signing"
            >
              位置签到
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 签到码输入对话框 -->
    <el-dialog
      v-model="codeDialogVisible"
      title="请输入签到码"
      width="30%"
      :close-on-click-modal="false"
    >
      <el-form :model="signForm" ref="signFormRef">
        <el-form-item
          prop="code"
          :rules="[{ required: true, message: '请输入签到码', trigger: 'blur' }]"
        >
          <el-input
            v-model="signForm.code"
            placeholder="请输入签到码"
            maxlength="20"
            show-word-limit
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="codeDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitCodeSign" :loading="signForm.loading">
            确认
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 九宫格签到对话框 -->
    <el-dialog
      v-model="gestureDialogVisible"
      title="九宫格签到"
      width="40%"
      :close-on-click-modal="false"
    >
      <el-form :model="gestureForm" ref="gestureFormRef">
        <el-form-item
          prop="gesturePoint"
          :rules="[{ required: true, message: '请输入九宫格手势密码', trigger: 'blur' }]"
        >
          <el-input
            v-model="gestureForm.gesturePoint"
            placeholder="请输入九宫格手势密码（如：1,2,3,4）"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="gestureDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitGestureSign" :loading="gestureForm.loading">
            确认
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 位置签到对话框 -->
    <el-dialog
      v-model="locationDialogVisible"
      title="位置签到"
      width="40%"
      :close-on-click-modal="false"
    >
      <el-form :model="locationForm" ref="locationFormRef" label-width="80px">
        <el-form-item
          prop="lat"
          :rules="[{ required: true, message: '请输入纬度', trigger: 'blur' }]"
          label="纬度"
        >
          <el-input
            v-model.number="locationForm.lat"
            placeholder="请输入纬度（如：39.9042）"
          />
        </el-form-item>
        <el-form-item
          prop="lon"
          :rules="[{ required: true, message: '请输入经度', trigger: 'blur' }]"
          label="经度"
        >
          <el-input
            v-model.number="locationForm.lon"
            placeholder="请输入经度（如：116.4074）"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="locationDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitLocationSign" :loading="locationForm.loading">
            确认
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 二维码扫描对话框 -->
    <el-dialog
      v-model="qrDialogVisible"
      title="扫描二维码"
      width="50%"
      :close-on-click-modal="false"
      destroy-on-close
    >
      <QRScanner @close="handleQRScannerClose" />
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'StudentActivitiesPage'
}
</script>

<script setup>
import { ref, onMounted, defineOptions } from 'vue'
import { ElMessage } from 'element-plus'
import { Refresh } from '@element-plus/icons-vue'
import { getPendingSignActivities, normalSign, codeSign, gestureSign, locationSign } from '@/api/student'
import dayjs from 'dayjs'
import QRScanner from '@/components/QRScanner.vue'

defineOptions({
  name: 'StudentActivitiesPage'
})

const loading = ref(false)
const activities = ref([])
const codeDialogVisible = ref(false)
const gestureDialogVisible = ref(false)
const locationDialogVisible = ref(false)
const qrDialogVisible = ref(false)
const signFormRef = ref(null)
const gestureFormRef = ref(null)
const locationFormRef = ref(null)
const currentActivity = ref(null)

const signForm = ref({
  code: '',
  loading: false
})

const gestureForm = ref({
  gesturePoint: '',
  loading: false
})

const locationForm = ref({
  lat: null,
  lon: null,
  loading: false
})

// 获取签到类型的标签类型
const getSignTypeTag = (type) => {
  const types = {
    normal: 'primary',
    code: 'warning',
    qr: 'success',
    gesture: 'info',
    location: 'danger'
  }
  return types[type] || 'eror'
}

// 获取签到类型的文本
const getSignTypeText = (type) => {
  const types = {
    normal: '普通签到',
    code: '签到码',
    qr: '二维码',
    gesture: '九宫格',
    location: '位置签到'
  }
  return types[type] || '未知类型'
}

// 格式化日期时间
const formatDateTime = (dateStr) => {
  return dayjs(dateStr).format('YYYY年MM月DD日 HH:mm:ss')
}

// 获取待签到活动列表
const fetchActivities = async () => {
  loading.value = true
  try {
    const response = await getPendingSignActivities()
    console.log('Activities Response:', response)
    if (response.code === 200) {
      activities.value = response.data.map(item => ({
        ...item,
        signing: false
      }))
    } else {
      ElMessage.error(response.message || '获取签到活动失败')
    }
  } catch (error) {
    console.error('获取签到活动失败:', error)
    ElMessage.error(error.response?.data?.message || '获取签到活动失败')
  } finally {
    loading.value = false
  }
}

// 普通签到
const handleNormalSign = async (activity) => {
  activity.signing = true
  try {
    const response = await normalSign(activity.id)
    console.log('Normal Sign Response:', response)
    if (response.code === 200) {
      ElMessage.success('签到成功')
      await fetchActivities() // 刷新列表
    } else {
      ElMessage.error(response.message || '签到失败')
    }
  } catch (error) {
    console.error('签到失败:', error)
    ElMessage.error(error.response?.data?.message || '签到失败')
  } finally {
    activity.signing = false
  }
}

// 打开签到码输入框
const handleCodeSign = (activity) => {
  currentActivity.value = activity
  signForm.value.code = ''
  codeDialogVisible.value = true
}

// 打开九宫格签到框
const handleGestureSign = (activity) => {
  currentActivity.value = activity
  gestureForm.value.gesturePoint = '1,2,3,4'
  gestureDialogVisible.value = true
}

// 打开位置签到框
const handleLocationSign = (activity) => {
  currentActivity.value = activity
  locationForm.value.lat = 2
  locationForm.value.lon = 2
  locationDialogVisible.value = true
}

// 打开二维码扫描
const handleQRSign = (activity) => {
  currentActivity.value = activity
  qrDialogVisible.value = true
}

// 处理二维码扫描结果
const handleQRScannerClose = (success) => {
  qrDialogVisible.value = false
  if (success) {
    fetchActivities() // 刷新列表
  }
}

// 提交签到码
const submitCodeSign = async () => {
  if (!signFormRef.value) return
  try {
    await signFormRef.value.validate()
    signForm.value.loading = true
    const response = await codeSign(currentActivity.value.id, signForm.value.code)
    console.log('Code Sign Response:', response)
    if (response.code === 200) {
      ElMessage.success('签到成功')
      codeDialogVisible.value = false
      await fetchActivities() // 刷新列表
    } else {
      ElMessage.error(response.message || '签到失败')
    }
  } catch (error) {
    console.error('签到失败:', error)
    ElMessage.error(error.response?.data?.message || '签到失败')
  } finally {
    signForm.value.loading = false
  }
}

// 提交九宫格签到
const submitGestureSign = async () => {
  if (!gestureFormRef.value) return
  try {
    await gestureFormRef.value.validate()
    gestureForm.value.loading = true
    const response = await gestureSign(currentActivity.value.id, 
      gestureForm.value.gesturePoint
    )
    console.log('Gesture Sign Response:', response)
    if (response.code === 200) {
      ElMessage.success('签到成功')
      gestureDialogVisible.value = false
      await fetchActivities() // 刷新列表
    } else {
      ElMessage.error(response.message || '签到失败')
    }
  } catch (error) {
    console.error('签到失败:', error)
    ElMessage.error(error.response?.data?.message || '签到失败')
  } finally {
    gestureForm.value.loading = false
  }
}

// 提交位置签到
const submitLocationSign = async () => {
  if (!locationFormRef.value) return
  try {
    await locationFormRef.value.validate()
    locationForm.value.loading = true
    const response = await locationSign(currentActivity.value.id, 
      locationForm.value.lat,
      locationForm.value.lon
    )
    console.log('Location Sign Response:', response)
    if (response.code === 200) {
      ElMessage.success('签到成功')
      locationDialogVisible.value = false
      await fetchActivities() // 刷新列表
    } else {
      ElMessage.error(response.message || '签到失败')
    }
  } catch (error) {
    console.error('签到失败:', error)
    ElMessage.error(error.response?.data?.message || '签到失败')
  } finally {
    locationForm.value.loading = false
  }
}

// 页面加载时获取活动列表
onMounted(() => {
  fetchActivities()
})
</script>

<style scoped>
.activities-page {
  max-width: 1200px;
  margin: 0 auto;
}

.activities-card {
  margin-top: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

:deep(.el-tag) {
  text-align: center;
  min-width: 80px;
}
</style>